// @ts-nocheck
import router from '@system.router';
import LogUtil from '../../common/baseUtil/LogUtil.js';
import CommonEvent from '@ohos.commonEvent';
import prompt from '@ohos.prompt';

let logUtil = new LogUtil();

export default {
    data: {
        isEventList: [],
        title: '',
        subscriber: null,
        event: ''
    },
    onInit() {
        logUtil.info('eventPage onInit  start:')
        let param = router.getParams();
        this.title = param.name + ' ' + this.$t('strings.eventTable')
        this.isEventList = param.dataParam || [];
        logUtil.info('eventPage get isEventList by json:' + JSON.stringify(this.isEventList))
        for (let key in this.isEventList) {
            var value = this.isEventList[key]
            var settingAlias = value.settingAlias
            value.settingTitle = this.$t('strings.'.concat(settingAlias))
        }
        this.event = param.event;
        let subscribeInfo = {events: [this.event]};
        CommonEvent.createSubscriber(subscribeInfo, this.createSubscriberCallBack);
        logUtil.info('eventPage onInit end:')
    },
    //创建订阅者回调
    createSubscriberCallBack(err, commonEventSubscriber) {
        if (err.code) {
            console.error("eventPage createSubscriber failed " + JSON.stringify(err));
        } else {
            this.subscriber = commonEventSubscriber;
            //订阅公共事件
            CommonEvent.subscribe(this.subscriber, this.subscribeCallBack);
        }
    },
    //订阅公共事件回调
    subscribeCallBack(err, data) {
        if (err.code) {
            console.error("eventPage subscribe failed " + JSON.stringify(err));
        } else {
            this.showToast('接收到广播：' + this.event);
            this.isEventList.forEach(element => {
                logUtil.info('eventPage subscribeCallBack :' + data.parameters[element.CommonEventBatteryCode])
                element.settingValue = data.parameters[element.CommonEventBatteryCode] + "";
            });
        }
    },
    showToast(msg) {
        prompt.showToast({
            message: msg,
            duration: 6000,
        });
    },
    onBackPress() {
        logUtil.info('eventPage onBackPress:')
        router.back();
    },
    onCreate() {
        logUtil.info('eventPage onCreate')
    },
    onReady() {
        logUtil.info('eventPage onReady')
    },
    onShow() {
        logUtil.info('eventPage onShow')
    },
    onHide() {
        logUtil.info('eventPage onHide')
    },
    onDestroy() {
        //取消订阅公共事件
        CommonEvent.unsubscribe(this.subscriber);
        logUtil.info('eventPage onDestroy')
    }
}